<template>
  <div class="workflow-manager">
    <el-tabs v-model="activeTab" class="workflow-tabs">
      <!-- 流程定义管理 -->
      <el-tab-pane label="流程定义" name="definitions">
        <div class="tab-content">
          <div class="toolbar">
            <el-button type="primary" @click="createWorkflow">
              <el-icon><Plus /></el-icon>
              新建流程
            </el-button>
            <el-button @click="refreshDefinitions">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
          
          <el-table :data="workflowDefinitions" v-loading="loading" stripe>
            <el-table-column prop="name" label="流程名称" min-width="150" />
            <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
            <el-table-column prop="version" label="版本" width="80" />
            <el-table-column prop="createdAt" label="创建时间" width="160">
              <template #default="{ row }">
                {{ formatDate(row.createdAt) }}
              </template>
            </el-table-column>
            <el-table-column prop="isActive" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.isActive ? 'success' : 'danger'">
                  {{ row.isActive ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="{ row }">
                <el-button size="small" @click="editWorkflow(row)">编辑</el-button>
                <el-button size="small" @click="startWorkflow(row)">启动</el-button>
                <el-button size="small" type="danger" @click="deleteWorkflow(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
      
      <!-- 流程实例管理 -->
      <el-tab-pane label="流程实例" name="instances">
        <div class="tab-content">
          <div class="toolbar">
            <el-button @click="refreshInstances">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
          
          <el-table :data="workflowInstances" v-loading="loading" stripe>
            <el-table-column prop="id" label="实例ID" width="180" show-overflow-tooltip />
            <el-table-column prop="definitionId" label="流程定义" min-width="150" show-overflow-tooltip />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="创建时间" width="160">
              <template #default="{ row }">
                {{ formatDate(row.createdAt) }}
              </template>
            </el-table-column>
            <el-table-column prop="createdBy" label="创建人" width="120" />
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="{ row }">
                <el-button size="small" @click="viewInstance(row)">查看</el-button>
                <el-button 
                  v-if="row.status === 'Running'" 
                  size="small" 
                  type="warning" 
                  @click="suspendInstance(row)"
                >
                  暂停
                </el-button>
                <el-button 
                  v-if="row.status === 'Suspended'" 
                  size="small" 
                  type="success" 
                  @click="resumeInstance(row)"
                >
                  恢复
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
      
      <!-- 我的任务 -->
      <el-tab-pane label="我的任务" name="tasks">
        <div class="tab-content">
          <div class="toolbar">
            <el-button @click="refreshTasks">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
          
          <el-table :data="myTasks" v-loading="loading" stripe>
            <el-table-column prop="id" label="任务ID" width="180" show-overflow-tooltip />
            <el-table-column prop="instanceId" label="流程实例" min-width="150" show-overflow-tooltip />
            <el-table-column prop="stepId" label="步骤" width="120" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getTaskStatusType(row.status)">
                  {{ getTaskStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="创建时间" width="160">
              <template #default="{ row }">
                {{ formatDate(row.createdAt) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <el-button 
                  v-if="row.status === 'Pending'" 
                  size="small" 
                  type="success" 
                  @click="approveTask(row)"
                >
                  审批
                </el-button>
                <el-button 
                  v-if="row.status === 'Pending'" 
                  size="small" 
                  type="danger" 
                  @click="rejectTask(row)"
                >
                  驳回
                </el-button>
                <el-button 
                  v-if="row.status === 'Pending'" 
                  size="small" 
                  @click="delegateTask(row)"
                >
                  委托
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>
    
    <!-- 流程设计器对话框 -->
    <el-dialog 
      v-model="showDesigner" 
      title="流程设计器" 
      width="95%" 
      :before-close="handleDesignerClose"
      class="designer-dialog"
    >
      <WorkflowDesigner 
        v-if="showDesigner" 
        :workflow-id="currentWorkflowId"
        @save="handleWorkflowSave"
        @close="showDesigner = false"
      />
    </el-dialog>
    
    <!-- 任务审批对话框 -->
    <el-dialog v-model="showTaskDialog" title="任务审批" width="500px">
      <el-form :model="taskForm" label-width="80px">
        <el-form-item label="操作">
          <el-radio-group v-model="taskForm.action">
            <el-radio label="Approve">同意</el-radio>
            <el-radio label="Reject">驳回</el-radio>
            <el-radio label="Delegate">委托</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item v-if="taskForm.action === 'Delegate'" label="委托给">
          <el-select v-model="taskForm.delegateTo" placeholder="选择委托人">
            <el-option 
              v-for="user in users" 
              :key="user.id" 
              :label="user.name" 
              :value="user.id" 
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="意见">
          <el-input 
            v-model="taskForm.comment" 
            type="textarea" 
            :rows="3"
            placeholder="请输入审批意见"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showTaskDialog = false">取消</el-button>
        <el-button type="primary" @click="submitTaskAction">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, defineAsyncComponent } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh } from '@element-plus/icons-vue'
const WorkflowDesigner = defineAsyncComponent(() => import('./WorkflowDesigner.vue'))
import WorkflowApiService from '../services/workflowApi'
import type { WorkflowDefinition, WorkflowInstance, WorkflowTask, User } from '../types/workflow'

// 响应式数据
const activeTab = ref('definitions')
const loading = ref(false)
const showDesigner = ref(false)
const showTaskDialog = ref(false)
const currentWorkflowId = ref('')

// 数据列表
const workflowDefinitions = ref<WorkflowDefinition[]>([])
const workflowInstances = ref<WorkflowInstance[]>([])
const myTasks = ref<WorkflowTask[]>([])
const users = ref<User[]>([])

// 任务表单
const taskForm = ref({
  taskId: '',
  action: 'Approve' as 'Approve' | 'Reject' | 'Delegate',
  comment: '',
  delegateTo: ''
})

// 初始化
onMounted(async () => {
  await loadInitialData()
  // 添加一些测试数据
  workflowDefinitions.value = [
    {
      id: '1',
      name: '请假申请流程',
      description: '员工请假申请审批流程，包含部门经理审批和人事审批',
      version: '1.0',
      createdAt: new Date(),
      isActive: true,
      steps: []
    },
    {
      id: '2', 
      name: '采购申请流程',
      description: '采购申请审批流程，包含预算审批、采购审批和财务审批',
      version: '1.0',
      createdAt: new Date(),
      isActive: true,
      steps: []
    },
    {
      id: '3',
      name: '合同审批流程', 
      description: '合同审批流程，包含法务审核、财务审核和总经理审批',
      version: '1.0',
      createdAt: new Date(),
      isActive: false,
      steps: []
    }
  ]
  
  workflowInstances.value = [
    {
      id: 'inst-001',
      definitionId: '1',
      status: 'Running',
      createdAt: new Date(),
      createdBy: '张三',
      data: {}
    },
    {
      id: 'inst-002',
      definitionId: '2', 
      status: 'Completed',
      createdAt: new Date(),
      createdBy: '李四',
      data: {}
    }
  ]
  
  myTasks.value = [
    {
      id: 'task-001',
      instanceId: 'inst-001',
      stepId: 'step-001',
      status: 'Pending',
      createdAt: new Date(),
      assignee: '王五'
    },
    {
      id: 'task-002',
      instanceId: 'inst-002',
      stepId: 'step-002', 
      status: 'Approved',
      createdAt: new Date(),
      assignee: '赵六'
    }
  ]
})

// 加载初始数据
const loadInitialData = async () => {
  try {
    loading.value = true
    const [usersRes] = await Promise.all([
      WorkflowApiService.getUsers()
    ])
    
    if (usersRes.success && usersRes.data) users.value = usersRes.data
  } catch (error) {
    console.error('加载初始数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 刷新流程定义
const refreshDefinitions = async () => {
  try {
    loading.value = true
    const response = await WorkflowApiService.getWorkflowDefinitions()
    if (response.success && response.data) {
      workflowDefinitions.value = response.data
    }
  } catch (error) {
    console.error('加载流程定义失败:', error)
    ElMessage.error('加载流程定义失败')
  } finally {
    loading.value = false
  }
}

// 刷新流程实例
const refreshInstances = async () => {
  try {
    loading.value = true
    const response = await WorkflowApiService.getWorkflowInstances()
    if (response.success && response.data) {
      workflowInstances.value = response.data
    }
  } catch (error) {
    console.error('加载流程实例失败:', error)
    ElMessage.error('加载流程实例失败')
  } finally {
    loading.value = false
  }
}

// 刷新我的任务
const refreshTasks = async () => {
  try {
    loading.value = true
    const response = await WorkflowApiService.getTasks()
    if (response.success && response.data) {
      myTasks.value = response.data
    }
  } catch (error) {
    console.error('加载我的任务失败:', error)
    ElMessage.error('加载我的任务失败')
  } finally {
    loading.value = false
  }
}

// 新建流程
const createWorkflow = () => {
  currentWorkflowId.value = ''
  showDesigner.value = true
}

// 编辑流程
const editWorkflow = (workflow: WorkflowDefinition) => {
  currentWorkflowId.value = workflow.id
  showDesigner.value = true
}

// 启动流程
const startWorkflow = async (workflow: WorkflowDefinition) => {
  try {
    const response = await WorkflowApiService.startWorkflow({
      definitionId: workflow.id,
      data: {}
    })
    
    if (response.success) {
      ElMessage.success('流程启动成功')
      refreshInstances()
    } else {
      ElMessage.error(response.message || '启动失败')
    }
  } catch (error) {
    console.error('启动流程失败:', error)
    ElMessage.error('启动流程失败')
  }
}

// 删除流程
const deleteWorkflow = async (workflow: WorkflowDefinition) => {
  try {
    await ElMessageBox.confirm('确定要删除这个流程吗？', '确认删除', {
      type: 'warning'
    })
    
    const response = await WorkflowApiService.deleteWorkflowDefinition(workflow.id)
    
    if (response.success) {
      ElMessage.success('删除成功')
      refreshDefinitions()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除流程失败:', error)
      ElMessage.error('删除流程失败')
    }
  }
}

// 查看实例
const viewInstance = (instance: WorkflowInstance) => {
  // TODO: 实现实例查看功能
  ElMessage.info('实例查看功能开发中')
}

// 暂停实例
const suspendInstance = async (instance: WorkflowInstance) => {
  try {
    const response = await WorkflowApiService.suspendWorkflow(instance.id)
    if (response.success) {
      ElMessage.success('实例已暂停')
      refreshInstances()
    }
  } catch (error) {
    console.error('暂停实例失败:', error)
    ElMessage.error('暂停实例失败')
  }
}

// 恢复实例
const resumeInstance = async (instance: WorkflowInstance) => {
  try {
    const response = await WorkflowApiService.resumeWorkflow(instance.id)
    if (response.success) {
      ElMessage.success('实例已恢复')
      refreshInstances()
    }
  } catch (error) {
    console.error('恢复实例失败:', error)
    ElMessage.error('恢复实例失败')
  }
}

// 审批任务
const approveTask = (task: WorkflowTask) => {
  taskForm.value = {
    taskId: task.id,
    action: 'Approve',
    comment: '',
    delegateTo: ''
  }
  showTaskDialog.value = true
}

// 驳回任务
const rejectTask = (task: WorkflowTask) => {
  taskForm.value = {
    taskId: task.id,
    action: 'Reject',
    comment: '',
    delegateTo: ''
  }
  showTaskDialog.value = true
}

// 委托任务
const delegateTask = (task: WorkflowTask) => {
  taskForm.value = {
    taskId: task.id,
    action: 'Delegate',
    comment: '',
    delegateTo: ''
  }
  showTaskDialog.value = true
}

// 提交任务操作
const submitTaskAction = async () => {
  try {
    const response = await WorkflowApiService.approveTask(taskForm.value.taskId, {
      taskId: taskForm.value.taskId,
      action: taskForm.value.action,
      comment: taskForm.value.comment,
      delegateTo: taskForm.value.delegateTo
    })
    
    if (response.success) {
      ElMessage.success('操作成功')
      showTaskDialog.value = false
      refreshTasks()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('任务操作失败:', error)
    ElMessage.error('任务操作失败')
  }
}

// 流程保存回调
const handleWorkflowSave = () => {
  showDesigner.value = false
  refreshDefinitions()
  ElMessage.success('流程保存成功')
}

// 设计器关闭处理
const handleDesignerClose = () => {
  showDesigner.value = false
}

// 工具函数
const formatDate = (date: Date | string) => {
  return new Date(date).toLocaleString()
}

const getStatusType = (status: string) => {
  const types: Record<string, string> = {
    'Running': 'success',
    'Completed': 'info',
    'Suspended': 'warning'
  }
  return types[status] || 'info'
}

const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    'Running': '运行中',
    'Completed': '已完成',
    'Suspended': '已暂停'
  }
  return texts[status] || status
}

const getTaskStatusType = (status: string) => {
  const types: Record<string, string> = {
    'Pending': 'warning',
    'Approved': 'success',
    'Rejected': 'danger',
    'Delegated': 'info'
  }
  return types[status] || 'info'
}

const getTaskStatusText = (status: string) => {
  const texts: Record<string, string> = {
    'Pending': '待处理',
    'Approved': '已同意',
    'Rejected': '已驳回',
    'Delegated': '已委托'
  }
  return texts[status] || status
}

defineOptions({
  name: 'WorkflowManager'
})
</script>

<style scoped>
.workflow-manager {
  padding: 20px;
  height: 100vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  width: 100%;
}

.workflow-tabs {
  flex: 1;
  display: flex;
  flex-direction: column;
  width: 100%;
}

.workflow-tabs :deep(.el-tabs__content) {
  flex: 1;
  overflow: hidden;
  width: 100%;
}

.workflow-tabs :deep(.el-tab-pane) {
  height: 100%;
  overflow: hidden;
  width: 100%;
}

.tab-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  width: 100%;
}

.toolbar {
  padding: 16px;
  border-bottom: 1px solid #e8e8e8;
  background: #fafbfc;
  flex-shrink: 0;
}

.toolbar .el-button {
  margin-right: 12px;
}

.el-table {
  flex: 1;
  overflow: auto;
  width: 100%;
}

/* 对话框样式 */
.designer-dialog {
  margin: 0;
}

.designer-dialog :deep(.el-dialog__body) {
  padding: 0;
  height: calc(100vh - 120px);
  overflow: hidden;
}

.designer-dialog :deep(.el-dialog) {
  margin: 10px;
  height: calc(100vh - 20px);
  max-width: 95vw;
}

/* 表格响应式优化 */
.el-table :deep(.el-table__body-wrapper) {
  overflow-x: auto;
}

.el-table :deep(.el-table__header-wrapper) {
  overflow-x: auto;
}

/* 确保表格内容不会溢出 */
.el-table :deep(.el-table__body),
.el-table :deep(.el-table__header) {
  min-width: 100%;
}
</style> 